#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#define OK 1
#define ERROR -1
#define OVERFLOW -2
typedef int Status;
typedef struct {
    char* ch;
    int length;
}HString;
Status StrAssign(HString &T, char* chars) {
    // if (T.ch)
    //     free(T.ch);
    int i = 0;
    char* c = chars;
    for (; *c; ++i,++c);
    if (!i) {
        T.ch = NULL;
        T.length = 0;
    } else {
        T.ch = (char*)malloc(sizeof(char) * i);
        if (!T.ch)
            exit(OVERFLOW);
        for (int c = 0; c < i; ++c) {
            T.ch[c] = chars[c];
        }
        T.length = i;
    }
    return OK;
}
Status StrLength(HString T) {
    return T.length;
}
Status StrCompare(HString T, HString S) {
    for (int i = 0; i < T.length && i < S.length; ++i) {
        if (T.ch[i] != S.ch[i])
            return T.ch[i] - S.ch[i];
    }
    return T.length - S.length;
}
Status ClearString(HString &T) {
    if (T.ch)
        free(T.ch);
    T.length = 0;
    return OK;
}
Status Concat(HString &T, HString S1, HString S2) {
    // if (T.ch)
    //     free(T.ch);
    T.ch = (char*)malloc(sizeof(char) * (S1.length + S2.length));
    for (int i = 0; i < S1.length; ++i)
        T.ch[i] = S1.ch[i];
    for (int i = 0; i < S2.length; ++i)
        T.ch[S1.length + i] = S2.ch[i];
    T.length = S1.length + S2.length;
    return OK;
}
Status SubString(HString &Sub, HString S, int pos, int len) {
    if (pos < 1 || pos > S.length || len < 0 || pos + len - 1 > S.length)
        return ERROR;
    // if (Sub.ch)
    //     free(Sub.ch);
    if (!len) {
        Sub.ch = NULL;
        Sub.length = 0;
    } else {
        Sub.ch = (char*)malloc(sizeof(char) * len);
        for (int i = 0; i < len; ++i)
            Sub.ch[i] = S.ch[pos-1+i];
        Sub.length = len;
    }
    return OK;   
}
void showStr(HString T) {
    for (int i = 0; i < T.length; ++i)
        printf("%c", T.ch[i]);
    printf("\n");
}
int main(void) {
    HString s1;
    HString s2;
    HString s3;
    HString s4;

    char c1[10] = "hello";
    char c2[10] = "world";
    StrAssign(s1, (char*)"hello");
    showStr(s1);
    StrAssign(s2, (char*)"world");
    showStr(s2);
    Concat(s3, s1, s2);
    showStr(s3);
    SubString(s4, s3, 1, 8);
    showStr(s4);

    return 0;
}